﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Text.RegularExpressions;
using OnlineVideos.ViewModels;
using System.Windows.Media.Imaging;
using Microsoft.Phone.BackgroundTransfer;
using Microsoft.Phone.Tasks;
using System.IO;
using System.Text;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using System.Diagnostics;
using Common.Library;
using OnlineVideos.Data;
//using MyToolkit.Multimedia;
using OnlineVideos.UI;
using System.ComponentModel;
using Common.Utilities;
using Microsoft.Phone.Info;
using OnlineVideos.Entities;
namespace OnlineVideos
{
    public partial class DownloadPivots : PhoneApplicationPage
    {
        #region GlobalDecularation
        List<string> downloadtitle = new List<string>();
        string[] regexImgSrc = { @"<a[^>]*?href\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>", @"<embed[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>", @"<iframe[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>", @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>", @"<video[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>", @"<link[^>]*?href\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>" };
        public ObservableCollection<DownloadPivot> Collection { get; set; }
        IEnumerable<DependencyObject> cboxes = null;
        List<DownloadPivot> YoutubeDownloadUrlList = new List<DownloadPivot>();
        public List<string> chkboxes = new List<string>();
        private static string result = null;

        List<Uri> Video = new List<Uri>();
        List<Uri> Audio = new List<Uri>();
        List<Uri> Image = new List<Uri>();
        List<Uri> Link = new List<Uri>();
        List<Uri> comparevideo = new List<Uri>();
        CustomizationSettings objCustom = new CustomizationSettings();
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
        string TitleForPromptFile = string.Empty;
        private static string metacafeurl = string.Empty;
        ObservableCollection<DownloadPivot> downloadForvimeolist = new ObservableCollection<DownloadPivot>();
        private static string CommanImageUrlForAllSites = string.Empty;
        int indexofvimeo = 0;
        int k = 0; 
        #endregion

        #region Initialize
        public DownloadPivots()
        {
            InitializeComponent();
            LoadPivotThemes();
            Loaded += new RoutedEventHandler(DownloadPivots_Loaded);
        } 
        #endregion

        #region Common Methods
        private void GetPageDataInBackground()
        {
            try
            {
                Video.Clear();
                Audio.Clear();
                Image.Clear();
                Link.Clear();
                Constants.SaveImages.Clear();
                Constants.SaveAudios.Clear();
                Constants.SaveVideos.Clear();
                Constants.SaveLinks.Clear();
                performanceProgressBar.IsIndeterminate = true;
                BackgroundHelper bhhelper = new BackgroundHelper();
                bhhelper.AddBackgroundTask((object s, DoWorkEventArgs a) =>
                {
                    DownloadManagerHelper.GetWebContent(regexImgSrc);
                },
                    (object s, RunWorkerCompletedEventArgs a) =>
                    {

                        Video.AddRange(Constants.SaveVideos);
                        Audio.AddRange(Constants.SaveAudios);
                        Image.AddRange(Constants.SaveImages);
                        Link.AddRange(Constants.SaveLinks);
                        LoadDownLoadVideos();
                        //LoadDownloadAudios();
                        //LoadImages();
                        LoadLinks();

                    }
                    );
              

                bhhelper.RunBackgroundWorkers();
                performanceProgressBar.IsIndeterminate = false;
            }
            catch (Exception ex)
            {
                string mess = "Exception in DownloadPivots_Loaded Method In downloadpivot.xaml.cs file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                ex.Data.Add("movieId", AppSettings.ShowID);
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void LoadLinks()
        {
            lbxlinks.Visibility = Visibility.Visible;
            ObservableCollection<DownloadPivot> download = new ObservableCollection<DownloadPivot>();
            try
            {

                if (Link.Count() != 0)
                {
                    download = DownloadManagerHelper.LoadLinks(Link);
                    lbxlinks.Visibility = Visibility.Visible;
                    lbxlinks.ItemsSource = download;

                }
                else
                {
                    lbxlinks.Visibility = Visibility.Collapsed;
                    tblkLinks.Visibility = Visibility.Visible;

                }

            }
            catch (Exception ex)
            {
                if (download.Count != 0)
                {
                    lbxlinks.ItemsSource = download;
                    lbxlinks.Visibility = Visibility.Visible;
                }
                else
                {
                    lbxlinks.Visibility = Visibility.Collapsed;
                    tblkLinks.Visibility = Visibility.Visible;

                    Exceptions.SaveOrSendExceptions("Exception in GetVideoLinksOfAMovie Method In OnlineShow.cs file", ex);
                }

            }

        }

        private void LoadImages()
        {
            ObservableCollection<DownloadPivot> download = new ObservableCollection<DownloadPivot>();
            try
            {
                string path;
                if (Image.Count() != 0)
                {
                    download = DownloadManagerHelper.LoadImages(Image);

                  
                }
                else
                {
                   
                }
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in LoadImages Method In downloadpivot.xaml.cs file", ex);
            }
            // performanceProgressBarvideo.IsIndeterminate = false;
        }

        private void LoadDownloadAudios()
        {
            try
            {
                ObservableCollection<DownloadPivot> download = new ObservableCollection<DownloadPivot>();
                if (Audio.Count() != 0)
                {
                   
                    Collection = DownloadManagerHelper.LoadAudios(Audio);
                   
                }
                else
                {
                   
                }
            }
            catch (Exception ex)
            {
                string mess = "Exception in LoadDownloadAudios Method In downloadpivot.xaml.cs file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                ex.Data.Add("movieId", AppSettings.ShowID);
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void LoadDownLoadVideos()
        {
            try
            {
                performanceProgressBarVideo.IsIndeterminate = true;

                ObservableCollection<DownloadPivot> download = new ObservableCollection<DownloadPivot>();

                if (Video.Count() != 0)
                {
                    string path = "";
                    int j = 0;
                    bool fal = false;
                    foreach (Uri u in Video)
                    {
                        if (u.ToString().StartsWith("http://"))
                        {

                            if (Video.ElementAt(indexofvimeo).ToString().StartsWith("http://vimeo.com") || Video.ElementAt(indexofvimeo).ToString().Contains("metacafe.com") || Video.ElementAt(indexofvimeo).ToString().Contains("sevenload.com"))
                            {
                                GetVideosFromVimeo(download);
                                break;

                            }
                            else if (Video.ElementAt(indexofvimeo).ToString().Contains("veoh.com") || Video.ElementAt(indexofvimeo).ToString().Contains("dailymotion.com") || Video.ElementAt(indexofvimeo).ToString().StartsWith("http://www.youtube.com/v/"))
                            {
                                GetVideosFromVeoh(download);
                                break;
                            }
                            else if (u.ToString().Contains(".ch9"))
                            {
                                if (u.ToString().EndsWith(".wmv"))
                                {
                                    DownloadPivot d = new DownloadPivot();
                                    d.title = u.ToString().Substring(u.ToString().LastIndexOf("/") + 1);
                                    d.Downloaduri = u;
                                    d.DownLoadVideoImage = u.ToString().Replace(".wmv", "").Replace(".mp4", "") + "_512.jpg";
                                    if (d.title != "")
                                        download.Add(d);
                                }
                                else if (u.ToString().EndsWith(".mp4"))
                                {
                                    DownloadPivot d = new DownloadPivot();
                                    d.title = u.ToString().Substring(u.ToString().LastIndexOf("/") + 1);
                                    d.Downloaduri = u;
                                    d.DownLoadVideoImage = u.ToString().Replace(".wmv", "").Replace(".mp4", "") + "_512.jpg";
                                    if (d.title != "")
                                        download.Add(d);
                                }
                            }

                            else
                            {
                                LoadWebItems(download, u);
                            }
                        }
                        else
                        {
                            DownloadPivot d = new DownloadPivot();
                            path = AppSettings.starturidownloadmanger + u.AbsolutePath.ToString();
                            d.title = path.Substring(path.ToString().LastIndexOf("/") + 1);
                            d.Downloaduri = new Uri(path);
                            if (d.title != "")
                                download.Add(d);
                        }
                    }

                    lbxVideo.ItemsSource = download;
                    lbxVideo.Visibility = Visibility.Visible;
                    YoutubeDownloadUrlList.AddRange(download);

                }
                else
                {
                    lbxVideo.Visibility = Visibility.Collapsed;
                    tblkFavNoMovies.Visibility = Visibility.Visible;
                    performanceProgressBarVideo.IsIndeterminate = false;
                }

            }
            catch (Exception ex)
            {
                string mess = "Exception in LoadDownLoadVideos Method In downloadpivot.xaml.cs file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                ex.Data.Add("movieId", AppSettings.ShowID);
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
            if (lbxVideo.Items.Count != 0)
            {
                performanceProgressBarVideo.IsIndeterminate = false;
            }
        }

        private void GetVideosFromVimeo(ObservableCollection<DownloadPivot> download)
        {
            try
            {
                string url = Video.ElementAt(indexofvimeo).ToString().ToString().Split('&')[0].TrimEnd(new char[] { '/' });
                metacafeurl = url;
                WebClient web = new WebClient();
                web.DownloadStringAsync(new Uri(url));
                web.DownloadStringCompleted += web_DownloadStringCompleted;
                if (downloadForvimeolist.Count != 0)
                    downloadForvimeolist[indexofvimeo - 1].YoutubeUrl = AppSettings.YoutubeUri;
                DownloadPivot d = new DownloadPivot();
                d.Downloaduri = new Uri(url);

                d.title = Regex.Split(Video.ElementAt(indexofvimeo).ToString(), "&")[1].Replace("title=", "").Replace(@"""", "");
                d.DownLoadVideoImage = Regex.Split(Video.ElementAt(indexofvimeo).ToString(), "&")[2].Replace("imageurl=", "").Replace(@"""", "");
                downloadForvimeolist.Add(d);
                foreach (var itm in downloadForvimeolist)
                {

                    download.Add(itm);
                }
                indexofvimeo++;
            }
            catch (Exception ex)
            {


            }
        }

        private void GetVideosFromVeoh(ObservableCollection<DownloadPivot> download)
        {
            try
            {
                string url = Video.ElementAt(indexofvimeo).ToString();
                metacafeurl = url;
                if (Video.ElementAt(indexofvimeo).ToString().Contains("dailymotion.com"))
                {
                    CommanImageUrlForAllSites = " http://www.dailymotion.com/thumbnail/160x120/video/" + url.ToString().Substring(url.ToString().LastIndexOf("/") + 1);
                }
                else if (Video.ElementAt(indexofvimeo).ToString().StartsWith("http://www.youtube.com/v/"))
                {
                    string youtubeurl = url.ToString().Substring(url.ToString().LastIndexOf("v/") + 2);
                    string yurl = youtubeurl.Replace("&amp;hl=en&amp;fs=1&amp;rel=0", "");
                    CommanImageUrlForAllSites = "http://img.youtube.com/vi/" + yurl + "/default.jpg";
                    url = "http://www.youtube.com/watch?v=" + yurl;
                }
                WebClient webForveoh = new WebClient();
                webForveoh.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
                webForveoh.DownloadStringAsync(new Uri(url));
                webForveoh.DownloadStringCompleted += webForveoh_DownloadStringCompleted;
                if (downloadForvimeolist.Count != 0)
                {
                    downloadForvimeolist[indexofvimeo - 1].YoutubeUrl = AppSettings.YoutubeUri;
                    downloadForvimeolist[indexofvimeo - 1].title = Regex.Split(AppSettings.Title, "&imageurl=")[0].Replace("(", "").Replace(")", "");
                    downloadForvimeolist[indexofvimeo - 1].DownLoadVideoImage = Regex.Split(AppSettings.Title, "&imageurl=")[1];
                }
                DownloadPivot d = new DownloadPivot();
                d.Downloaduri = new Uri(url);
                downloadForvimeolist.Add(d);
                foreach (var itm in downloadForvimeolist)
                {

                    download.Add(itm);

                }
                download.RemoveAt(downloadForvimeolist.Count - 1);
                indexofvimeo++;
            }
            catch (Exception ex)
            {


            }
        }

        private static void LoadWebItems(ObservableCollection<DownloadPivot> download, Uri u)
        {
            DownloadPivot d = new DownloadPivot();
            d.title = u.ToString().Substring(u.ToString().LastIndexOf("/") + 1);
            d.Downloaduri = u;
            if (d.title != "")
                download.Add(d);
        }

        private void LoadPivotThemes()
        {

        }

        public void GetYoutubeTitle(string uri)
        {
            WebClient wcl = new WebClient();
            wcl.DownloadStringCompleted += wcl_DownloadStringCompleted;
            wcl.DownloadStringAsync(new Uri(uri));
        }

        public void ChannelCh()
        {
            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += WcChannelCh_DownloadStringCompleted;
            wc.DownloadStringAsync(new Uri(AppSettings.NavigationUrl));

        }
        
        #endregion

        #region Events
       
        void wcl_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
               string title=string.Empty;
               string Downloadurl = string.Empty;
                BackgroundHelper bhhelper = new BackgroundHelper();
                bhhelper.AddBackgroundTask((object s, DoWorkEventArgs a) =>
                 {
                     title = DownloadManagerHelper.GetTitle(e.Result);
                     Downloadurl = DownloadManagerHelper.GethtmlData(e.Result);
                 },
                     (object s, RunWorkerCompletedEventArgs a) =>
                     {
                         if (title != null)
                         {
                             downloadtitle.Add(title + "@" + Downloadurl);
                         }
                         LoadDownLoadVideos();
                     });
                bhhelper.RunBackgroundWorkers();
            }

            catch (Exception)
            {


            }
        }

        private void webForveoh_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                string VideoTitle = string.Empty;
                AppSettings.YoutubeUri = string.Empty;
                AppSettings.Title = string.Empty;
                if (metacafeurl.Contains("dailymotion.com"))
                {
                    AppSettings.YoutubeUri = DownloadManagerDailyMotion.dailyDownload(e.Result, dailyQuality.ld);
                    VideoTitle = DownloadManagerDailyMotion.GetDailymotionVideoTitle(e.Result);
                    VideoTitle = VideoTitle + "&imageurl=" + CommanImageUrlForAllSites;
                    AppSettings.Title = VideoTitle;
                    LoadDownLoadVideos();
                }
                else if (metacafeurl.Contains("veoh.com"))
                {
                    AppSettings.YoutubeUri = DownloadManagerDailyMotion.GetVideoUrlForVeohSite(e.Result);
                    VideoTitle = Regex.Match(e.Result, @"\<title\s?.*?\>((.|\r\n)+?)\<\/title\>").Groups[1].Value.Replace("Veoh.com", "").Replace("|", "").Replace("&amp", "").Replace("#", "").Replace("0", "").Replace("1", "").Replace("2", "").Replace("3", "").Replace("4", "").Replace("5", "").Replace(";", "").Replace("6", "").Replace("7", "").Replace("8", "").Replace("9", "");
                    string Image = Regex.Split(e.Result, "image")[1];
                    string imageurl = Image.Split('>')[0].Replace("content=", "").Replace(@"""", "");
                    VideoTitle = VideoTitle + "&imageurl=" + imageurl;
                    AppSettings.Title = VideoTitle;
                    LoadDownLoadVideos();
                }
                else if (metacafeurl.Contains("youtube.com"))
                {
                    VideoTitle = DownloadManagerHelper.GetTitle(e.Result);
                    Int64 result = (Int64)DeviceExtendedProperties.GetValue("ApplicationWorkingSetLimit");
                    try
                    {
                        if (result < 94371840L)
                        {
                            AppSettings.YoutubeUri = DownloadManagerHelper.GetYoutuVidoesUrlFor3Gpp(e.Result);
                        }
                        else
                        {
                            AppSettings.YoutubeUri = DownloadManagerHelper.GethtmlData(e.Result);
                        }
                    }
                    catch (Exception ex)
                    {

                    }

                    VideoTitle = VideoTitle + "&imageurl=" + CommanImageUrlForAllSites;
                    AppSettings.Title = VideoTitle;
                    LoadDownLoadVideos();
                }


            }
            catch (Exception ex)
            {
                string mes = ex.Message;
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
        }

        void DownloadPivots_Loaded(object sender, RoutedEventArgs e)
        {

            Collection = new ObservableCollection<DownloadPivot>();
            GetPageDataInBackground();
        }

        private void img1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {


        }

        private void appbar_button1_Click(object sender, EventArgs e)
        {
            BackgroundHelper bhhelper = new BackgroundHelper();
            bhhelper.AddBackgroundTask((object s, DoWorkEventArgs a) =>
            {
                DownloadManagerHelper.AppbarDownloadClick(chkboxes, YoutubeDownloadUrlList);
            },
                (object s, RunWorkerCompletedEventArgs a) =>
                {
                    Constants.DownloadStatus = false;
                    NavigationService.Navigate(new Uri("/Views/ShowList.xaml?index=" + 2, UriKind.Relative));

                });
            bhhelper.RunBackgroundWorkers();
        }

        void web_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (metacafeurl.Contains("metacafe.com"))
            {
                AppSettings.YoutubeUri = DownloadManagerDailyMotion.GetDownloadVideoUrlFromMetacafeSite(e.Result);
            }
            else if (metacafeurl.Contains("vimeo.com"))
            {
                AppSettings.YoutubeUri = DownloadManagerDailyMotion.GetDownloadvideoUrlforVimeoSite(e.Result);
            }
            else
            {
                AppSettings.YoutubeUri = "http://ak.cdn.sevenload.net/slcom-production/cdn/" + metacafeurl.Substring(metacafeurl.LastIndexOf("-") + 1) + "/mobile-h264.main-md.mp4";
            }

            LoadDownLoadVideos();
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/Downloding.xaml", UriKind.Relative));
        }

        private void chkVideo_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                chkboxes = DownloadManagerHelper.CheckBoxCheckedItemList(lbxVideo);
            }
            catch (Exception ex)
            {
                string mess = "Exception in chkAudio_Checked Method In DownloadPivots.xaml file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void chkVideo_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                chkboxes = DownloadManagerHelper.CheckBoxUnCheckedItemList(lbxVideo);
            }
            catch (Exception ex)
            {
                string mess = "Exception in chkVideo_Unchecked Method In DownloadPivots.xaml file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void menuItemdownload_Click(object sender, EventArgs e)
        {
            try
            {
                if (chkboxes.Count() != 0)
                {
                    foreach (string s in chkboxes)
                    {
                        DownloadManager.Savetofolder("", s);


                    }
                    SettingsHelper.Save("DownloadFolder", "0");
                    NavigationService.Navigate(new Uri("/Views/SaveFolderName.xaml", UriKind.Relative));
                }
            }
            catch (Exception ex)
            {
                string mess = "Exception in menuItemdownload_Click Method In DownloadPivots.xaml file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void imgTitle_MouseEnter(object sender, MouseEventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void WcChannelCh_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string html = e.Result.ToString();
            string RegexForFrame = @"<frame[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
            MatchCollection fram = Regex.Matches(html, RegexForFrame, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            foreach (Match m in fram)
            {
                string href = m.Groups[1].Value;
                if (href.ToString().StartsWith("http://sharesix.com"))
                {
                    WebClient wc12 = new WebClient();
                    wc12.DownloadStringCompleted += Wcsharesix_DownloadStringCompleted;
                    wc12.DownloadStringAsync(new Uri(href));

                }
                if (href.ToString().StartsWith("http://www.promptfile.com"))
                {
                    WebClient wcpromptfile = new WebClient();
                    wcpromptfile.DownloadStringCompleted += wcpromptfile_DownloadStringCompleted;
                    wcpromptfile.DownloadStringAsync(new Uri(href));
                    Match Title = Regex.Match(html, @"\<title\s?.*?\>((.|\r\n)+?)\<\/title\>");
                    TitleForPromptFile = Title.Groups[1].Value;
                }
            }
        }

        private void wcpromptfile_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string html1 = e.Result.ToString();
            string Regexfordiv = @"\<div\s?.*?\>((.|\r\n)+?)\<\/div\>";
            MatchCollection fram1 = Regex.Matches(html1, Regexfordiv, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            foreach (Match m1 in fram1)
            {

                Match GetUrl = Regex.Match(m1.ToString(), @"<a[^>]*?href\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                if (GetUrl.ToString().Contains("http://www.promptfile.com"))
                {
                    string Url = GetUrl.Groups[1].Value.Replace("==", "");
                    string OriginalUrl = Url + "=" + TitleForPromptFile + ".mkv";
                    Video.Add(new Uri(OriginalUrl));
                    LoadDownLoadVideos();
                    lbxVideo.Visibility = Visibility.Visible;
                    tblkFavNoMovies.Visibility = Visibility.Collapsed;

                }


            }
        }

        private void Wcsharesix_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string html1 = e.Result.ToString();
            string Regexforscript = @"\<script\s?.*?\>((.|\r\n)+?)\<\/script\>";
            Match mth = Regex.Match(html1, @"\<Title\s?.*?\>((.|\r\n)+?)\<\/Title\>");
            MatchCollection fram1 = Regex.Matches(html1, Regexforscript, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            foreach (Match m1 in fram1)
            {
                string scriptgroup = m1.Groups[1].Value.Replace("</script>\n", "");
                if (scriptgroup.StartsWith("<script type='text/javascript'>eval"))
                {
                    string rate = scriptgroup.Substring(scriptgroup.LastIndexOf("addParam|") + 9).Replace("player|", "");
                    string PlayerUrl = rate.Substring(rate.LastIndexOf("video|") + 6).Split('|')[0];
                    string PlayerID = rate.Split('f')[0].Replace("|", "._").Replace("._._", "");
                    string[] arrayid = PlayerID.Split('_');
                    string orignalid = null;
                    int i = 0;
                    foreach (string s in arrayid.Reverse())
                    {
                        i++;
                        if (arrayid.Count() != i)
                            orignalid = orignalid + s + ".";
                        else
                            orignalid = orignalid + s.Replace(".", "");
                    }
                    string DownloadUrl = "http://" + orignalid.Replace("..", ".") + "/d/" + PlayerUrl + "/" + mth.Groups[1].Value + ".mp4";
                    Video.Add(new Uri(DownloadUrl));
                    LoadDownLoadVideos();
                    lbxVideo.Visibility = Visibility.Visible;
                    tblkFavNoMovies.Visibility = Visibility.Collapsed;

                }

            }
        }

        private void lbxlinks_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbxlinks.SelectedIndex != -1)
            {
                performanceProgressBar.IsIndeterminate = true;

                Uri href = (lbxlinks.SelectedItem as DownloadPivot).Downloaduri;
                try
                {
                    WebClient webcli = new WebClient();
                    webcli.DownloadStringCompleted += webcli_DownloadStringCompleted;
                    webcli.DownloadStringAsync(new Uri(href.ToString()));
                    AppSettings.NavigationUrl = href.ToString();
                }
                catch (Exception ex)
                {
                    string mess = "Exception in lbxlinks_SelectionChanged Method In DownloadPivots.xaml file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                    Exceptions.SaveOrSendExceptions(mess, ex);
                }
                lbxlinks.SelectedIndex = -1;

            }
        }

        void webcli_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            tblkLinks.Visibility = Visibility.Collapsed;
            tblkFavNoMovies.Visibility = Visibility.Collapsed;
            lbxVideo.Visibility = Visibility.Visible;
            lbxlinks.Visibility = Visibility.Visible;
            Video.Clear();
            Image.Clear();
            Link.Clear();
            if (AppSettings.NavigationUrl.StartsWith("http://www.1channel.ch"))
            {
                ChannelCh();
            }
            if(e.Result!=null)
            AppSettings.htmltextfordownloadmanger = e.Result;
            performanceProgressBar.IsIndeterminate = true;
            GetPageDataInBackground();
        }

        private void lbxVideo_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            var selecteditem = lbxVideo.SelectedItem as DownloadPivot;
            if (selecteditem.Downloaduri.ToString().StartsWith("http://www.youtube.com"))
            {
                string linkurl = selecteditem.YoutubeUrl;
                DownloadManagerHelper.PlayStreamVideo(linkurl);
            }
            else
            {
                YoutubeApi.Youtube.PlayYoutubeVideo((selecteditem.Downloaduri.ToString()));
        
            }
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                IEnumerable<System.Windows.Navigation.JournalEntry> back = NavigationService.BackStack.ToList();
                foreach (var b in back)
                {
                    if (!b.Source.ToString().Contains("MainPage.xaml"))
                        NavigationService.RemoveBackEntry();
                    //break;
                }
            }
            catch (Exception ex)
            {
                string mess = "Exception in chk_Checked Method In DownloadPivots.xaml file\n\n" + ex.Message + " \n\n Stack Trace \n" + ex.StackTrace;
                Exceptions.SaveOrSendExceptions(mess, ex);
            }
        }

        private void appbariconaddvideos_Click_1(object sender, EventArgs e)
        {
            List<DownloadPivot> listpivot = new List<DownloadPivot>();
            try
            {
                if (chkboxes.Count() != 0)
                {
                    listpivot.AddRange(lbxVideo.Items.Cast<DownloadPivot>());
                    foreach (string s in chkboxes)
                    {
                        if (s.StartsWith("http://www.youtube.com"))
                        {
                            string youtubeurl = s.Substring(s.LastIndexOf("v/") + 2);
                            string yurl = youtubeurl.Replace("&amp;hl=en&amp;fs=1&amp;rel=0", "").Replace("&hl=en&fs=1&rel=0", "");
                            // DownloadManager.SaveDownloadingInfo("", "http://www.youtube.com/watch?v=" + yurl);
                        }
                        DownloadPivot item = listpivot.Where(i => i.Downloaduri == new Uri(s)).FirstOrDefault();
                        DownloadManager.SaveAddVideoLinks(item.Downloaduri.ToString(), item.title, item.DownLoadVideoImage, int.Parse(AppSettings.ShowID));
                    }
                    PageHelper.NavigateToDetailPage(AppResources.DetailPageName, AppSettings.ShowID);
                }
            }
            catch (Exception ex)
            {
                string mess = "Exception in chk_Checked Method In DownloadPivots.xaml file";
                Exceptions.SaveOrSendExceptions(mess, ex);
            }

        }
        #endregion

      
    }
  

}